<template>
  <div class="app-container">
    <div v-has-perm="['nljs_indicator_category_view']" class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="分类名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div v-has-perm="['nljs_indicator_category_add']" class="mb-10px">
        <el-button type="success" icon="plus" @click="handleOpenDialog('0')">新增</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="indicatorCategoryTableData"
        highlight-current-row
        row-key="id"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
      >
        <el-table-column label="分类名称" align="left" min-width="150" prop="name" />
        <el-table-column label="分类编码" align="left" min-width="150" prop="code" />
        <el-table-column label="备注" align="left" min-width="150" prop="remark" />
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-has-perm="['nljs_indicator_category_add']"
              type="primary"
              link
              size="small"
              icon="plus"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              新增
            </el-button>

            <el-button
              v-has-perm="['nljs_indicator_category_edit']"
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(undefined, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-has-perm="['nljs_indicator_category_del']"
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      :size="drawerSize"
      @close="handleCloseDialog"
    >
      <el-form ref="indicatorCategoryFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="父级分类" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            placeholder="选择上级分类"
            :data="indicatorCategoryOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类编码" prop="name">
          <el-input v-model="formData.code" placeholder="请输入分类编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            placeholder="请输入备注"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from '@/store/modules/app.store';
import { DeviceEnum } from '@/enums/settings/device.enum';
import DeptAPI from '@/api/system/dept.api';
import IndiactorAPI, { IndicatorCategoryInfo } from '@/api/batch/indicator.api';

defineOptions({
  name: 'indicator-category',
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const indicatorCategoryFormRef = ref();

const loading = ref(false);
const dialog = reactive({
  title: '新增分类',
  visible: false,
});

const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? '600px' : '90%'));
// 查询参数
const queryParams = reactive<any>({ parentId: '0' });
// 分类表格数据
const indicatorCategoryTableData = ref<IndicatorCategoryInfo[]>([]);
// 顶级分类下拉选项
const indicatorCategoryOptions = ref<OptionType[]>([]);
// 初始分类表单数据
const initialindicatorCategoryFormData = ref<any>({
  name: '',
  code: '',
  parentId: '',
  areaId: '',
  energyType: '',
});
// 分类表单数据
const formData = ref({ ...initialindicatorCategoryFormData.value });
// 表单验证规则
const rules = reactive({
  parentId: [{ required: true, message: '请选择父级分类', trigger: 'blur' }],
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入分类编码', trigger: 'blur' }],
  areaId: [{ required: true, message: '请选择所属区域', trigger: 'blur' }],
});

// 查询分类
function handleQuery() {
  loading.value = true;
  IndiactorAPI.getIndicatorCategoryTree()
    .then((data: any) => {
      indicatorCategoryTableData.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

const buildTree = (data: any) => {
  return data.map((item: any) => {
    const children = item.children || [];
    return {
      value: item.id,
      label: item.name,
      children: children.length > 0 ? buildTree(children) : [],
    };
  });
};

/**
 * 打开表单弹窗
 *
 * @param parentId 父分类ID
 * @param indicatorCategoryId 分类ID
 */
function handleOpenDialog(parentId?: string, row?: any) {
  IndiactorAPI.getIndicatorCategoryTree()
    .then((data: any) => {
      indicatorCategoryOptions.value = [
        { value: '0', label: '顶级分类', children: data ? buildTree(data) : [] },
      ];
    })
    .then(() => {
      dialog.visible = true;
      if (row) {
        dialog.title = '编辑分类';
        formData.value = { ...row, id: row.id };
      } else {
        dialog.title = '新增分类';
        formData.value.parentId = parentId?.toString();
      }
    });
}

/**
 * 提交表单
 */
function handleSubmit() {
  indicatorCategoryFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const indicatorCategoryId = formData.value.id;
      const indicatorCategoryParams = { ...formData.value };
      console.log('indicatorCategoryParams-', indicatorCategoryParams);
      if (indicatorCategoryId) {
        //修改时父级分类不能为当前分类
        if (formData.value.parentId == indicatorCategoryId) {
          ElMessage.error('父级分类不能为当前分类');
          return;
        }
        IndiactorAPI.editIndicatorCategory(formData.value).then(() => {
          ElMessage.success('修改成功');
          handleCloseDialog();
          handleQuery();
        });
      } else {
        if (!indicatorCategoryParams?.params?.length) {
          delete indicatorCategoryParams.params;
        }
        IndiactorAPI.addIndicatorCategory(indicatorCategoryParams).then(() => {
          ElMessage.success('新增成功');
          handleCloseDialog();
          handleQuery();
        });
      }
    }
  });
}

// 删除分类
function handleDelete(indicatorCategoryId: any) {
  if (!indicatorCategoryId) {
    ElMessage.warning('请勾选删除项');
    return false;
  }

  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(
    () => {
      loading.value = true;
      IndiactorAPI.delIndicatorCategory(indicatorCategoryId)
        .then(() => {
          ElMessage.success('删除成功');
          handleQuery();
        })
        .finally(() => {
          loading.value = false;
        });
    },
    () => {
      ElMessage.info('已取消删除');
    }
  );
}

function resetForm() {
  indicatorCategoryFormRef.value.resetFields();
  indicatorCategoryFormRef.value.clearValidate();
  formData.value = {
    id: undefined,
    parentId: '0',
    name: '',
    code: '',
    sort: 0,
    areaId: '',
    energyType: '',
    params: [],
  };
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>
